package xyz.zhouxf.rpc.handler;

import xyz.zhouxf.rpc.entity.RpcRequest;
import xyz.zhouxf.rpc.provider.ServiceProvider;
import xyz.zhouxf.rpc.provider.impl.DefaultServiceProvider;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

/**
 * @author zhouxf
 * @date 2022/8/31
 */
public class RpcHandler {

    private static final ServiceProvider serviceProvider;

    static {
        serviceProvider = new DefaultServiceProvider();
    }

    public Object handle(RpcRequest rpcRequest) {
        Object service = serviceProvider.getService(rpcRequest.getInterfaceName());
        return invokeMethod(rpcRequest, service);
    }

    private Object invokeMethod(RpcRequest rpcRequest, Object service) {
        Object result = null;
        try {
            Method method = service.getClass().getMethod(rpcRequest.getMethodName(), rpcRequest.getParamTypes());
            result = method.invoke(service, rpcRequest.getParams());
        } catch (NoSuchMethodException | IllegalAccessException | InvocationTargetException e) {

        }
        return result;
    }

}
